package com.xiaomi.web.handlers;

import com.xiaomi.domain.UserEntity;
import com.xiaomi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Random;

@Controller
@RequestMapping("/user")
public class UserHandler {
    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping("/getVerifyCode")
    public Integer getVerifyCode(HttpSession session){
        Random random = new Random();
        Integer verifyCode = random.nextInt(10000);
        session.setAttribute("verifyCode",String.valueOf(verifyCode));
        return verifyCode;

    }
    @ResponseBody
    @RequestMapping("/login")
    public boolean login(String phone,String verifyCode,HttpSession session){
        if (!session.getAttribute("verifyCode").equals(verifyCode)){
            return false;
        }
        UserEntity user = userService.getUserByPhone(phone);
        session.setAttribute("user",user);
        return true;
    }

    @RequestMapping("/isRegister")
    @ResponseBody
    public boolean isRegisterByPhone(String phone,String username){
        boolean flag = userService.isRegister(phone,username);
        return flag;
    }

    @RequestMapping("/register")
    public String register( MultipartFile photo_, UserEntity user, HttpServletRequest request){
        String realPath = request.getServletContext().getRealPath("/img");
        boolean flag = userService.register(user,realPath,photo_);

        if (flag == false){
            return "admin/error";
        }else {
            return "redirect:/login.jsp";
        }
    }
}
